package com.aistar.controller;

import com.aistar.pojo.Member;
import com.aistar.pojo.PageEs;
import com.aistar.pojo.Travelnote;
import com.aistar.service.MemberService;
import com.aistar.service.es_search.ES_SearchService;
import com.aistar.service.es_search.impl.TravelnoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.Map;

@Controller
public class SearchEngineController {
    @Qualifier("TravelnoteES_SearchServiceImpl")
    @Autowired
    private ES_SearchService travelnoteService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    TravelnoteRepository travelnoteRepository;

    @Autowired
    MemberService memberService;

    @RequestMapping("search/keywords/{content}")
    public ModelAndView queryIndexByElastic2(@PathVariable("content") String content, HttpServletRequest request){
        PageEs<Travelnote> pageData = new PageEs();
        pageData.setCurrPage(1);
        pageData.setPageSize(8);
        PageEs<Travelnote> pageEs = travelnoteService.queryResult(pageData,content);
        Page<Travelnote> travelnotes = pageEs.getDataList();
        Map<Travelnote, Member> map = new LinkedHashMap<>();
        for (Travelnote travelnote:travelnotes
        ) {
            System.out.println(travelnote.getTravText()+'\n');
            Member member = memberService.getbyId(travelnote.getTravWid());
            map.put(travelnote,member);
        }
        System.out.println("map.size():"+map.size());


        Object ss = request.getSession().getAttribute("userId");//获得session里的用户id
        int userId = Integer.parseInt(String.valueOf(ss));
        Member member = memberService.getbyId(userId);


        ModelAndView mov = new ModelAndView();
        mov.setViewName("Search/search_result");
        mov.addObject("map",map);
        mov.addObject("memberall",member);
        return mov;
    }
    /**
     * 分词查找，最大优点！！！！
     */
}